import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Tag, PaginationResponse, QueryParams } from '@/types/admin'
import { api, API_ENDPOINTS } from '@/utils/api'
import { ElMessage } from 'element-plus'

export const useTagStore = defineStore('tag', () => {
  // 状态
  const tags = ref<Tag[]>([])
  const currentTag = ref<Tag | null>(null)
  const pagination = ref({
    page: 1,
    limit: 20,
    total: 0,
    pages: 0
  })
  const isLoading = ref(false)
  const allTags = ref<Tag[]>([])

  // 获取标签列表
  const fetchTags = async (params: QueryParams = {}) => {
    try {
      isLoading.value = true
      
      // 构建查询参数
      const queryParams: any = {
        page: params.page || 1,
        limit: params.limit || 20
      }
      
      // 添加其他查询参数
      if (params.search) queryParams.search = params.search
      if (params.isActive !== undefined) queryParams.isActive = params.isActive
      if (params.orderBy) queryParams.orderBy = params.orderBy
      if (params.order) queryParams.order = params.order
      
      const response = await api.get<PaginationResponse<Tag>>(
        API_ENDPOINTS.TAGS,
        queryParams
      )
      
      if (response.data?.data && response.data?.pagination) {
        tags.value = response.data.data
        pagination.value = {
          page: response.data.pagination.page,
          limit: response.data.pagination.limit,
          total: response.data.pagination.total,
          pages: response.data.pagination.pages
        }
      } else if (Array.isArray(response.data)) {
        tags.value = response.data
        const returnedCount = response.data.length
        const requestedLimit = queryParams.limit
        const currentPage = queryParams.page
        
        const hasMoreData = returnedCount === requestedLimit
        let estimatedTotal: number
        
        if (currentPage === 1 && !hasMoreData) {
          estimatedTotal = returnedCount
        } else if (!hasMoreData) {
          estimatedTotal = (currentPage - 1) * requestedLimit + returnedCount
        } else {
          estimatedTotal = currentPage * requestedLimit + 1
        }
        
        pagination.value = {
          page: currentPage,
          limit: requestedLimit,
          total: estimatedTotal,
          pages: Math.ceil(estimatedTotal / requestedLimit)
        }
      } else {
        tags.value = []
        pagination.value = {
          page: 1,
          limit: 20,
          total: 0,
          pages: 0
        }
      }
      
    } catch (error) {
      console.error('获取标签列表失败:', error)
      ElMessage.error('获取标签列表失败')
      tags.value = []
      pagination.value = {
        page: 1,
        limit: 20,
        total: 0,
        pages: 0
      }
    } finally {
      isLoading.value = false
    }
  }

  // 获取标签详情
  const fetchTagById = async (id: number) => {
    try {
      isLoading.value = true
      const response = await api.get<Tag>(`${API_ENDPOINTS.TAGS}/${id}`)
      if (response.data) {
        currentTag.value = response.data
      }
      return response.data
    } catch (error) {
      console.error('获取标签详情失败:', error)
      ElMessage.error('获取标签详情失败')
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 根据slug获取标签
  const fetchTagBySlug = async (slug: string) => {
    try {
      isLoading.value = true
      const response = await api.get<Tag>(`${API_ENDPOINTS.TAGS}/slug/${slug}`)
      if (response.data) {
        currentTag.value = response.data
      }
      return response.data
    } catch (error) {
      console.error('获取标签详情失败:', error)
      ElMessage.error('获取标签详情失败')
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 创建标签
  const createTag = async (tagData: Partial<Tag>) => {
    try {
      const response = await api.post<Tag>(API_ENDPOINTS.TAGS, tagData)
      if (response.data) {
        tags.value.unshift(response.data)
        ElMessage.success('标签创建成功')
        return response.data
      }
    } catch (error) {
      console.error('创建标签失败:', error)
      ElMessage.error('创建标签失败')
      throw error
    }
  }

  // 更新标签
  const updateTag = async (id: number, tagData: Partial<Tag>) => {
    try {
      const response = await api.put<Tag>(`${API_ENDPOINTS.TAGS}/${id}`, tagData)
      if (response.data) {
        const index = tags.value.findIndex(t => t.id === id)
        if (index !== -1) {
          tags.value[index] = response.data
        }
        if (currentTag.value?.id === id) {
          currentTag.value = response.data
        }
        ElMessage.success('标签更新成功')
        return response.data
      }
    } catch (error) {
      console.error('更新标签失败:', error)
      ElMessage.error('更新标签失败')
      throw error
    }
  }

  // 删除标签
  const deleteTag = async (id: number) => {
    try {
      await api.delete(`${API_ENDPOINTS.TAGS}/${id}`)
      tags.value = tags.value.filter(t => t.id !== id)
      if (currentTag.value?.id === id) {
        currentTag.value = null
      }
      ElMessage.success('标签删除成功')
    } catch (error) {
      console.error('删除标签失败:', error)
      ElMessage.error('删除标签失败')
      throw error
    }
  }

  // 批量删除标签
  const deleteTagsBatch = async (ids: number[]) => {
    try {
      await api.post(`${API_ENDPOINTS.TAGS}/batch/delete`, { ids })
      tags.value = tags.value.filter(t => !ids.includes(t.id))
      ElMessage.success(`成功删除 ${ids.length} 个标签`)
    } catch (error) {
      console.error('批量删除标签失败:', error)
      ElMessage.error('批量删除标签失败')
      throw error
    }
  }

  // 切换标签状态
  const toggleTagStatus = async (id: number, isActive: boolean) => {
    try {
      const response = await api.put<Tag>(`${API_ENDPOINTS.TAGS}/${id}`, { isActive })
      if (response.data) {
        const index = tags.value.findIndex(t => t.id === id)
        if (index !== -1) {
          tags.value[index] = response.data
        }
        ElMessage.success(`标签已${isActive ? '启用' : '禁用'}`)
        return response.data
      }
    } catch (error) {
      console.error('切换标签状态失败:', error)
      ElMessage.error('切换标签状态失败')
      throw error
    }
  }

  // 清空当前标签
  const clearCurrentTag = () => {
    currentTag.value = null
  }

  // 重置状态
  const reset = () => {
    tags.value = []
    currentTag.value = null
    pagination.value = {
      page: 1,
      limit: 20,
      total: 0,
      pages: 0
    }
    isLoading.value = false
  }

  // 获取所有标签
  const fetchAllTags = async () => {
    try {
      const response = await api.get<{ data: Tag[] }>(API_ENDPOINTS.TAGS, {
        limit: 1000,
        page: 1
      })
      
      if (Array.isArray(response.data)) {
        allTags.value = response.data
      } else if (response.data && Array.isArray(response.data.data)) {
        allTags.value = response.data.data
      }
      
      return allTags.value
    } catch (error) {
      console.error('获取所有标签失败:', error)
      return []
    }
  }

  return {
    // 状态
    tags,
    currentTag,
    pagination,
    isLoading,
    allTags,

    // 方法
    fetchTags,
    fetchTagById,
    fetchTagBySlug,
    createTag,
    updateTag,
    deleteTag,
    deleteTagsBatch,
    toggleTagStatus,
    clearCurrentTag,
    reset,
    fetchAllTags
  }
}) 